from django.shortcuts import render
from django.http import HttpResponseRedirect
from Store.models import *
from .forms import RegisterForm
from .forms import UserInfoForm
from .forms import PersonForm
from django.http import JsonResponse

import hashlib


def setpassword(password):
    md5 = hashlib.md5()
    md5.update(password.encode())
    result = md5.hexdigest()
    return result


def LoginValid(func):
    def inner(request, *args, **kwargs):
        cookie_userid = request.COOKIES.get("userid")
        session_userid = request.session.get("userid")
        cookieusername = request.COOKIES.get("username")
        if cookie_userid and session_userid:
            flag = QUser.objects.filter(
                id=session_userid,
                username=cookieusername,
                usertype=1
            ).exists()
            if flag:
                return func(request, *args, **kwargs)
        return HttpResponseRedirect("store/login/")

    return inner


def reqtest(request):
    print(request.method)
    print(request.POST.get("username"))
    return render(request, "demo.html", locals())


def register(request):
    message = ""
    if request.method == "POST":
        print(request.POST)
        registerform = RegisterForm(request.POST)
        if registerform.is_valid():
            data = registerform.cleaned_data
            username = data.get("username")
            email = request.POST.get("email")
            password = request.POST.get("password")
            repassword = request.POST.get("repassword")
            phone = request.POST.get("phone")
            code = request.POST.get("code")
            if password and password == repassword:
                # 校验验证码
                checkcode = CheckCode.objects.filter(phone=phone, code=code).order_by("-create_time").first()
                if checkcode:
                    # 存在
                    # 校验 是否再有效期内 2分钟
                    create_time = checkcode.create_time  # 获取创建时间
                    now_time = datetime.now()  # 当前时间
                    # 计算两个时间的差值
                    t = (now_time - create_time).total_seconds()
                    if t <= 120:
                        # 代表有效
                        flag = QUser.objects.filter(username=username).exists()
                        if not flag:
                            QUser.objects.create(
                                username=username,
                                email=email,
                                password=setpassword(password),
                                usertype=1,
                                phone=phone
                            )
                            # 重定向
                            return HttpResponseRedirect("/store/login/")
                        else:
                            message = "账号已存在"
                    else:
                        message = "验证码失效"
                else:
                    message = "验证码不存在"
            else:
                message = "密码不符合"
        else:
            errors = registerform.errors

    return render(request, "store/register.html", locals())


# 短信验证
from sdk.ytxcode import send_message
import random
from datetime import datetime


def getcode(request):
    result = {}
    # 获取手机号
    phone = request.GET.get("phone")
    # 生成code
    code = random.randint(1000, 9999)
    # 发送验证码 调用三方
    params = {
        "tid": "1",
        "mobile": phone,
        "code": str(code),
        "time": "2",  # 2分钟有效期
    }
    send_message(params)
    # 保存数据
    CheckCode.objects.create(
        phone=phone,
        code=str(code),
        create_time=datetime.strftime(datetime.now(), "%Y-%m-%d %H:%M:%S")
    )
    result = {
        "code": "0000",
        "msg": "验证码已发送"
    }
    return JsonResponse(result)


def login(request):
    message = ""
    if request.method == "POST":
        # print(request.POST)
        username = request.POST.get("username")
        password = request.POST.get("password")
        if username and password:
            flag = QUser.objects.filter(
                username=username,
                password=setpassword(password)
            ).first()
            if flag:
                resp = HttpResponseRedirect("/store/index/")
                resp.set_cookie("username", flag.username)
                resp.set_cookie("userpicture", flag.picture)
                resp.set_cookie("userid", flag.id)
                request.session["userid"] = flag.id
                return resp
            else:
                message = "账号不存在，请先注册"
    return render(request, "store/login.html", locals())


@LoginValid
def userinfo(request):
    # 获取用户信息 get请求
    userid = request.session.get("userid")
    userinfo = QUser.objects.get(id=userid)
    # 处理post请求
    if request.method == "POST":
        # print(request.POST)
        userinfoform = UserInfoForm(request.POST)  # 实例化forms类，并传递获取的数据
        if userinfoform.is_valid():
            data = userinfoform.cleaned_data
            # 处理 保存数据
            userinfo.nickname = data.get("nick_name")
            gender = request.POST.get("gender")
            if gender == "":
                gender = userinfo.gender
            userinfo.gender = gender
            userinfo.phone = data.get("phone")
            userinfo.email = data.get("email")
            userinfo.address = data.get("address")
            if request.FILES.get("picture"):
                userinfo.picture = request.FILES.get("picture")
            userinfo.save()
            return HttpResponseRedirect("/store/index/")
        else:
            errors = UserInfoForm.errors
            print(errors)
        # 处理校验结果
    return render(request, "store/userinfo.html", locals())


def logout(request):
    resp = HttpResponseRedirect("/store/login/")
    resp.delete_cookie("userid")
    resp.delete_cookie("username")
    del request.session["userid"]
    return resp


# @LoginValid
# from django.views.decorators.cache import cache_page
# @cache_page(2*60)    # 2分钟
# from .tasks import say, addnum
# import time
def index(request):
    # res = addnum.delay(10)
    # print(res)
    return render(request, "store/index.html", locals())


from celery.result import AsyncResult


def getres(request):
    task_id = ""
    data = AsyncResult(task_id)
    print(data.result)


import random



def goods(request):
    goods_type = GoodsType.objects.all()
    userid = request.session.get("userid")
    # print(userid)
    if request.method == "POST":
        goods = Goods()
        print(request.POST.get("goods_type"))
        goods.g_name = request.POST.get("goods_name")
        goods.g_number = random.randint(1, 1000)
        goods.g_price = request.POST.get("g_price")
        goods.g_safe_date = request.POST.get("g_safe_date")
        goods.g_description = request.POST.get("g_description")
        goods.g_picutre = request.FILES.get("g_picture")
        goods.g_num = request.POST.get("goods_number")
        goods.g_type_id = int(request.POST.get("goods_type"))
        goods.g_store = Store.objects.filter(s_user_id=userid).first()
        goods.save()

    # 商品显示
    goods_list = Goods.objects.filter(
        g_store=Store.objects.filter(
            s_user_id=userid
        ).first()
    ).all()
    return render(request, "store/goods.html", locals())


# 商品类型数量
def goodsnumapi(request):
    # 商品类型 : 数量
    result = {
        "data": []
    }
    userid = request.session.get("userid")
    # 商品类型
    from django.db.models import Sum
    data = Goods.objects.filter(g_store=Store.objects.filter(
        s_user_id=userid
    ).first()
                                ).values('g_type_id__t_name').annotate(Sum('g_num'))
    for one in data:
        result['data'].append(
            {'name': one.get('g_type_id__t_name'),
             'num': one.get('g_num__sum')
             }
        )
    return JsonResponse(result)


@LoginValid
def statistics_goods(request):
    return render(request, "store/statistics_goods.html", locals())


@LoginValid
def statistics_orders(request):
    return render(request, "store/statistics_orders.html", locals())


import os


@LoginValid
def store(request):
    userid = request.session.get("userid")
    store_obj = Store.objects.filter(s_user_id=userid).first()
    if request.method == "POST":
        from Qshop.settings import BASE_DIR
        img = request.FILES.get("s_logo")
        print(dir(img))
        print(img.name)  # 图片名字
        static_path = os.path.join(
            os.path.join(os.path.join(BASE_DIR, "static"), "store"), "images")
        # 保存图片
        # 图片保存地址
        db_path = os.path.join("store", os.path.join("images", img.name))
        # 写入文件
        with open(os.path.join(static_path, img.name), "wb") as f:
            for content in img.chunks():
                f.write(content)
        store = Store()
        store.s_name = request.POST.get("s_name")
        store.s_logo = db_path
        store.s_address = request.POST.get("s_address")
        store.s_description = request.POST.get("s_description")
        store.s_user_id = userid
        store.save()
    return render(request, "store/store.html", locals())


# from django.http import HttpResponse
# def middlewaretest(request):
#     a = [1,2,3]
#     print(a[3])
#     print("view")
#     # return HttpResponse("view")
#     return render(request,"store/404.html",{"name","lisi"})
#
#     # def func1():
#     #     return render(request,"store/404.html")
#     # resp = HttpResponse("nihao")
#     # resp.render = func1
#     # return resp

@LoginValid
def orders(request):
    return render(request, "store/orders.html", locals())


def test_form(request):
    # personform = PersonForm()
    if request.method == "POST":
        print(request.POST)
        # 获取数据
        # 后端校验
        personform = PersonForm(request.POST)  # 实例化forms类，并传递获取的数据
        if personform.is_valid():
            # True代表校验通过
            print("success")
            # 处理数据 获取通过校验之后的数据
            data = personform.cleaned_data
            print(data)
            # 处理 保存数据
        else:
            # False 代表校验失败
            print("error")
            errors = personform.errors
            print(errors)
        # 处理校验结果
    return render(request, "forms.html", locals())


def jsontest(request):
    res = {"code": 1000, "name": "zs"}
    for key, value in res.items():
        print(key, value)
    # res = ["code",1000]
    return JsonResponse(res)


def ajaxtest(request):
    result = {
        "code": "10000",
        "msg": "请求成功",
        "data": {}
    }
    userid = request.GET.get("id")
    person = QUser.objects.filter(id=userid).first()
    result["data"] = {
        "username": person.username,
        "password": person.password,
        "nickname": person.nickname,
        "picture": str(person.picture),
    }
    resp = JsonResponse(result)
    resp["Access-Control-Allow-Origin"] = "*"
    return resp


def vuedemo(request):
    return render(request, "vuedemo.html")


def list_login(request):
    result = {
        "data": [
        ]
    }
    goods_list = Goods.objects.filter()[0:8]
    print(goods_list)

    for one in goods_list:
        # print(one)
        data = {"g_name": one.g_name, "g_price": one.g_price, "g_picutre": str(one.g_picutre)}
        result["data"].append(data)
    print(result)
    return JsonResponse(result)


def list_login1(request):
    result = {
        "data": []
    }
    goods_list = Goods.objects.filter()[0:8]
    print(goods_list)
    for one in goods_list:
        result["data"].append({
            "g_name": one.g_name,
            "g_price": one.g_price,
            "g_picutre": str(one.g_picutre)
        })
        print()
    return JsonResponse(result)


from django.views.decorators.csrf import csrf_exempt


@csrf_exempt
def fundemo(request):
    if request.method == "GET":
        return JsonResponse({"methods": "get"})

    if request.method == "POST":
        return JsonResponse({"methods": "post"})

    if request.method == "PUT":
        return JsonResponse({"methods": "puT"})

    import json
    if request.method == "DELETE":
        return JsonResponse({"methods": "delete"})


from django.views.decorators.csrf import csrf_exempt
from django.utils.decorators import method_decorator
from django.views import View


@method_decorator(csrf_exempt, 'dispatch')
class GoodsView(View):
    # 封装init方法
    def __init__(self):
        self.result = {
            "code": "200",
            "msg": "success",
            "data": [],
            "methods": ""
        }

    # 处理get请求
    def get(self, request):
        # 获取数据
        # 有参数
        self.result["methods"] = "get"
        id = request.GET.get('id')
        if id:
            # 处理id
            goods_obj = Goods.objects.filter(id=id).first()
            self.result["data"] = {
                "g_name": goods_obj.g_name,
                "g_number": goods_obj.g_number,
                "g_price": goods_obj.g_price,
                "g_description": goods_obj.g_description
            }
        else:

            # 没有参数
            goods_list = Goods.objects.all()[:12]
            for one in goods_list:
                goods_obj = {
                    "g_name": one.g_name,
                    "g_number": one.g_number,
                    "g_price": one.g_price,
                    "g_description": one.g_description,
                }
                self.result["data"].append(goods_obj)
        return JsonResponse(self.result)

    # 处理post请求
    def post(self, request):
        # 创建数据
        # 获取数据
        data = request.POST
        # 添加数据
        goods_obj = Goods()
        goods_obj.g_name = data.get("g_name")
        goods_obj.g_number = data.get("g_number")
        goods_obj.g_price = data.get("g_price")
        goods_obj.g_description = data.get("g_description")
        goods_obj.g_safe_date = data.get("g_safe_date")
        goods_obj.g_picutre = data.get("g_picutre")
        goods_obj.g_num = data.get("g_num")
        goods_obj.save()
        self.result["methods"] = "post"
        return JsonResponse(self.result)

    # 处理put请求
    def put(self, request):
        # 更新数据
        data = request.body  # bytes类型
        data = request.body.decode()  # 字符串类型json
        import json
        # # 第一种
        # data = json.loads(request.body.decode())
        # id = data.get("id")
        # goods = Goods.objects.filter(id = id).first()
        # data.pop("id")
        # for key,value in data.items():
        #     # 设置属性 为对象重新赋值 修改
        #     # 判断 获取到的key 是否为对象的属性
        #     if hasattr(goods,key):
        #         setattr(goods,key,value)
        # goods.save()

        # 第二种
        data = json.loads(request.body.decode())
        id = data.get("id")
        data.pop("id")
        # 修改数据
        Goods.objects.filter(id=id).update(**data)
        return JsonResponse(self.result)

    # 处理delete请求

    def delete(self, request):
        # 删除数据
        import json
        id = json.loads(request.body.decode()).get("id")
        Goods.objects.filter(id=id).delete()
        return JsonResponse({"methods": "delete"})


# # DRF
# # 1、APIView
from rest_framework.views import APIView, Response
from .serializer import MoreListSerializer
# # class MorelistView(APIView):
#     # 处理get请求
#     def get(self,request):
#         # 返回10条数据
#         goods_list = Goods.objects.all()[:10]
#         serializer = MoreListSerializer(goods_list,many=True)   #many=True结果中使用列表得形式
#         result = serializer.data  # 要返回的数据
#         return Response(result)
#
from rest_framework.views import APIView, Response
from .serializer import QuserListSerializer


class QuserlistView(APIView):
    # 处理get请求
    def get(self, request):
        # 返回10条数据
        user_list = QUser.objects.all()[:10]
        serializer = QuserListSerializer(user_list, many=True)  # many=True结果中使用列表得形式
        result = serializer.data  # 要返回的数据
        return Response(result)


# 2、mixins类
# from rest_framework import mixins,generics
# class MorelistView(mixins.ListModelMixin,generics.GenericAPIView):
#     def get_queryset(self):
#         # # 获取到一个queryset结果
#         # goods_list = Goods.objects.all()[:10]
#         # 返回某个商品的10条数据
#         type_id = self.request.GET.get("type_id")
#         goods_list = GoodsType.objects.filter(id = type_id).first().goods_set.all()
#         return goods_list
#     # 序列化器
#     serializer_class = MoreListSerializer
#
#     def get(self,request, *args, **kwargs):
#         # 处理get请求
#         return self.list(request, *args, **kwargs)
#
#     # 返回数据 让结果保持原有的样子
#     def get_serializer_context(self):
#         return {
#             "view":self
#         }


# # 3、通用视图类
# from rest_framework import generics
# class MorelistView(generics.ListAPIView):
#     def get_queryset(self):
#         # 获取到一个queryset结果
#         # goods_list = Goods.objects.all()[:10]
#         # 返回某个商品的10条数据
#         type_id = self.request.GET.get("type_id")
#         goods_list = GoodsType.objects.filter(id = type_id).first().goods_set.all()
#         return goods_list
#     # 序列化器
#     serializer_class = MoreListSerializer
#
#     # 返回数据 让结果保持原有的样子
#     def get_serializer_context(self):
#         return {
#             "view":self
#         }


# 4、ViewSet类和路由器
from rest_framework import viewsets


class MorelistView(viewsets.ReadOnlyModelViewSet):
    def get_queryset(self):
        # 获取到一个queryset结果
        # goods_list = Goods.objects.all()[:10]
        # 返回某个商品的10条数据
        type_id = self.request.GET.get("type_id")
        goods_list = GoodsType.objects.filter(id=type_id).first().goods_set.all()
        return goods_list

    # 序列化器
    serializer_class = MoreListSerializer

    # 返回数据 让结果保持原有的样子
    def get_serializer_context(self):
        return {
            "view": self
        }


# import random
# from django.http import HttpResponse
# def add_goods(request):
#     ## 添加店铺
#     store = Store.objects.create(s_name="生鲜店", s_logo="1.jpg", s_address="北京", s_description="北京生鲜店",
#                                  s_user=QUser.objects.get(id=1))
#     ## 添加类型
#     goodstype = GoodsType.objects.create(t_name="生鲜", t_description="生鲜店",t_img="1.jpg")
#     ## 增加100 条  
#     goods_name = "芹菜、西芹、菠菜、香菜、茼蒿、茴香、生菜、苋菜、莴苣、葱、香葱、分葱、胡葱、楼子葱、蒜头、洋葱头、韭菜、韭葱、黄瓜、丝瓜、冬瓜、菜瓜、苦瓜、南瓜、栉瓜、西葫芦、葫芦、瓠瓜、节瓜、越瓜、笋瓜、佛手瓜"
#     goods_name = goods_name.split("、")
#     address = "北京市，天津市，上海市，重庆市，河北省，山西省，辽宁省，吉林省，黑龙江省，江苏省，浙江省，安徽省，福建省，江西省，山东省，河南省，湖北省，湖南省，广东省，海南省，四川省，贵州省，云南省，陕西省，甘肃省，青海省，台湾省"
#     address = address.split("，")
#     for n in range(10):
#         for i, j in enumerate(range(10), 1):  ## i 是索引 代表下标从1开始
#             goods = Goods()
#             goods.g_number = str(i).zfill(5)  ## 返回指定长度的字符串   长度是5 
#             goods.g_name = random.choice(address) + random.choice(goods_name)  ###从列表中随机取一个值  
#             goods.g_price = round(random.random() * 100, 2)  ## 0到1 的小数  
#             goods.g_num = random.randint(1, 100)
#             goods.g_safe_date = random.randint(1, 12)
#             goods.g_desription = "很好"
#             goods.g_picutre = "images/goods.jpg"
#             goods.g_type = goodstype
#             goods.g_store = store
#             goods.save()
#     return HttpResponse("添加数据")

from django.core.cache import cache
# 缓存操作
# def getgoodsname(request):
#     # id = 2 的商品
#     id = 2
#     # 使用get方法 获取缓存
#     data = cache.get('goods_2')
#     print(1)
#     # 存在
#     if data is not None:
#         # 返回 使用print
#         print(2)
#         print(data)
#     # 不存在
#     else:
#         print(3)
#         # 查询数据库
#         goods_name = Goods.object.filter(id = id).first().g_name
#         # 设置缓存 set
#         # set(key,values,time)
#         cache.set('goods_2',goods_name,20)
#     return HttpResponse("缓存操作")
#
# def updategoods(request):
#     id =3
#     # 判断 id=3的商品信息是否存在缓存中
#     data = cache.get("goods_3")
#     if data is not None:
#         # 如果存在 删除
#         cache.delete("goods_3")
#     # 更新数据库的信息
#     Goods.object.filter(id = 3).update(g_name = "西瓜")
#     # 选择性的将结果设置到缓存中
#     return HttpResponse("更新商品")
